#ifndef USER_H
#define USER_H

#include "MsgModPC.h"
#include "Defines.h"
#include <iostream>

using std::cout;
using std::endl;

class CUser : public CMsgModPC
{
public:
	typedef string T_UserUniqueID;
	typedef enum T_UserStatus
	{
		InHall,
		InRoom,
		Gaming
	};
	T_UserUniqueID ID;
	string UserName;
	SOCKET Socket;
	T_UserStatus Status;
	bool IsHost;
	int IsPlayer;

	T_ModuleDescriptor Room;

public:
	CUser(T_UserUniqueID id) : ID(id), IsHost(0), IsPlayer(-1), Room(-1) {}
	CUser(string name, SOCKET sock) : UserName(name), ID(name), Socket(sock), IsHost(0), IsPlayer(-1), Room(-1) {}
	//~CUser() { closesocket(Socket); }

	void Exit()
	{
		if ( Room != -1)
			POST_MSG_TO( Room, MSG_PLAYER_EXIT, GetMD(), (char *)0 );
	}

	int Send(const char *buf, int nbytes)
	{
		if (Socket > 0)
			return send(Socket, buf, nbytes, 0);
		else return -1;
	}

	virtual void MOnRecvMsg(unsigned int type, T_LParameter lp, const DataFlow &data)
	{
		long int ret;
		T_ModuleDescriptor md = lp;
		switch (type)
		{
		case MSG_PLAYER_JOIN_ACCEPT:
			if ( (Room != -1) && (Room == md) && (IsPlayer = -1) )
			{
				memcpy (&ret, data.GetData(), sizeof(ret));
				IsPlayer = ret;
				cout << UserName << " join in room "<< md <<" as player " << ret << endl;
			}
			break;
		case MSG_PLAYER_JOIN_DENY:
			if ( (Room != -1) && (Room == md) && (IsPlayer = -1) )
			{
				Room = -1;
				cout << UserName << " join in deny" << endl;
			}
			break;
		case MSG_GAME_START_ACCEPT:
			if (Room == md)
				cout << UserName << " game start!" << endl;
			break;
		case MSG_GAME_START_DENY:
			if (Room == md)
			{
				cout << UserName << " game could not start because " << data.GetData() << endl;
			}
			break;
		case MSG_GAME_PACKET:
			if (Room == md)
				Send(data.GetData(), data.GetLength());
			break;
		}
	}
	void JoinGame(T_ModuleDescriptor game, bool host)
	{
		if ( (Room == -1) && (IsPlayer = -1) && (!IsHost) )
		{
			IsHost = host;
			Room = game;
			POST_MSG_TO(game, host ? MSG_PLAYER_HOST_JOIN : MSG_PLAYER_JOIN, GetMD(), ID);
		}
	}
	void StartGame()
	{
		if ( (Room != -1) && (IsPlayer != -1) && (IsHost) )
		{	
			POST_MSG_TO(Room, MSG_GAME_START, GetMD(), (char *)0 );
		}
	}
};



















#endif